<template>
  <div class="app-container">
    <el-row :gutter="20" class="question-edit-contain">
      <el-col :span="24">
        <el-card>
          <el-form
            :model="form"
            ref="form"
            label-width="100px"
            v-loading="formLoading"
            :rules="rules"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所属人员类型：" label-width="120px" required>
                  <el-select
                    class="filter-item"
                    v-model="form.personnelType"
                    :clearable="true"
                    placeholder=""
                    filterable
                    :disabled="personnelTypeDisable"
                  >
                    <el-option
                      v-for="item in personnelTypeList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="试卷名称：" label-width="120px" prop="paperName" required>
                  <el-input v-model="form.paperName"> </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="试卷总分：" label-width="120px" prop="totalScore">
                  <el-input v-model="form.totalScore"> </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合格分：" label-width="120px" prop="passScore">
                  <el-input v-model="form.passScore"> </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-card class="box-card" style="height: 350px; overflow-y: auto">
              <div slot="header" class="clearfix">
                <span style="font-size: 16px; font-weight: bold">试卷内容</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click="addSubject()"
                  >添加试题</el-button
                >
              </div>
              <div v-for="(item, index) in form.subjects" :key="item.detailId" class="text item">
                <el-row :gutter="20">
                  <el-col :span="20">
                    <div>{{ index + 1 }}、{{ item.subjectTitle }}</div>
                    <div>
                      <span v-for="option in item.options" :key="option.optionId">
                        {{ option.optionTitle }} {{ option.optionContent }}</span
                      >
                    </div>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="danger" size="small" @click="removeSubject(item)"
                      >删除</el-button
                    >
                  </el-col>
                </el-row>
              </div>
            </el-card>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item>
                  <el-button type="primary" @click="submitForm">提交</el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { DictionaryController, BizExamPaperController, BizSubjectController } from '@/api';
import formsChooseBizExamPaper from '@/views/biz/formsChooseBizExamPaper/index.vue';
export default {
  name: 'formsEditBizExamPaper',
  props: {
    rowData: Object
  },
  data() {
    return {
      form: {
        paperId: null,
        personnelType: null,
        moduleType: 3,
        paperName: null,
        totalScore: 0,
        passScore: 0,
        subjects: []
      },
      personnelTypeDisable: this.rowData.paperId != null,
      personnelTypeList: [],
      formLoading: false,
      rules: {
        paperName: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
        personnelType: [{ required: true, message: '请选择人员类型', trigger: 'change' }]
      }
    };
  },
  created() {
    this.loadPersonnelTypeDropdownList();
  },
  methods: {
    onCancel(isSuccess = false) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.subjects.length === 0) {
            this.$message.warning('请录入试题!');
            return false;
          }
          this.formLoading = true;
          BizExamPaperController.edit(this, this.form)
            .then(re => {
              if (re.errorCode === 'NO-ERROR') {
                this.$message.success('操作成功');
                this.onCancel(true);
                this.$router.replace({ name: 'formsBizExamPaper' });
              } else {
                this.$message.error('操作失败');
                console.error(re.errorMessage);
              }
            })
            .finally(() => {
              this.formLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    resetForm() {
      this.form = {
        paperId: null,
        personnelType: null,
        paperName: null,
        totalScore: 0,
        passScore: 0,
        subjects: []
      };
      this.$refs['form'].resetFields();
    },
    loadPersonnelTypeDropdownList() {
      return new Promise((resolve, reject) => {
        let params = {
          dictCode: 'PersonnelType'
        };
        DictionaryController.dictGlobalDict(this, params)
          .then(res => {
            this.personnelTypeList = res.getList();
            this.personnelTypeList = this.personnelTypeList.filter(item => {
              return item.id !== '1';
            });
          })
          .catch(e => {
            reject(e);
          });
      });
    },
    loadExistSubjectData() {
      return new Promise((resolve, reject) => {
        let params = {
          paperId: this.form.paperId
        };
        BizExamPaperController.detail(this, params).then(res => {
          this.form.subjects = res.data;
        });
      });
    },
    addSubject() {
      let data = { ...this.rowData, includedSubjects: this.form.subjects };
      if (this.form.personnelType === '1' || !this.form.personnelType) {
        this.$message.warning('请选择具体的人员类型!');
        return false;
      }
      if (!data.personnelType) {
        data = { ...data, personnelType: this.form.personnelType };
      }
      this.$dialog
        .show(
          '选择试题',
          formsChooseBizExamPaper,
          {
            area: '960px'
          },
          {
            rowData: data
          }
        )
        .then(res => {
          this.form.subjects = res;
          this.form.totalScore = this.form.subjects.reduce(
            (sum, item) => sum + (item.subjectScore || 0),
            0
          );
        })
        .catch(e => {});
    },
    removeSubject(subject) {
      this.form.subjects = this.form.subjects.filter(item => item.subjectId !== subject.subjectId);
      this.form.totalScore = this.form.subjects.reduce(
        (sum, item) => sum + (item.subjectScore || 0),
        0
      );
    }
  },
  mounted() {
    if (Object.keys(this.rowData).length > 0) {
      this.form.paperId = this.rowData.paperId;
      this.form.personnelType = this.rowData.personnelType + '';
      this.form.paperName = this.rowData.paperName;
      this.form.totalScore = this.rowData.totalScore;
      this.form.passScore = this.rowData.passScore;
    }
    if (Object.keys(this.rowData).length > 0 && this.rowData.paperId) {
      this.loadExistSubjectData();
    }
  }
};
</script>
<style type="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
  padding: 20px;
}
</style>
